package fr.lille.inria.adam.lifl.EcoGardeInventory.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import android.util.SparseIntArray;
import android.widget.SectionIndexer;

public class StringListIndexer implements SectionIndexer {
	HashMap<String, Integer> letterToPos;
	SparseIntArray posToLetter;
	String[] sections;
	
	public StringListIndexer(ArrayList<String> objects) {
		ArrayList<String> elements = objects;
		// here is the tricky stuff
		letterToPos = new HashMap<String, Integer>(); 
		// in this hashmap we will store here the positions for
		// the sections

		int size = elements.size();
		for (int i = size - 1; i >= 0; i--) {
			String element = elements.get(i);
			if (element==null || element.length()<1) continue;
			letterToPos.put(element.substring(0, 1), i);
		//We store the first letter of the word, and its index.
		//The Hashmap will replace the value for identical keys are putted in
		} 

		// now we have an hashmap containing for each first-letter
		// sections(key), the index(value) in where this sections begins

		// we have now to build the sections(letters to be displayed)
		// array .it must contains the keys, and must (I do so...) be
		// ordered alphabetically

		Set<String> keys = letterToPos.keySet(); // set of letters ...sets
		// cannot be sorted...

		Iterator<String> it = keys.iterator();
		ArrayList<String> keyList = new ArrayList<String>(); // list can be
		// sorted

		while (it.hasNext()) {
			String key = it.next();
			keyList.add(key);
		}

		Collections.sort(keyList);

		sections = new String[keyList.size()]; // simple conversion to an
		// array of object
		keyList.toArray(sections);
		
		posToLetter = new SparseIntArray(letterToPos.size());
		for (int itLetter = 0; itLetter < sections.length; itLetter++) {
			String letter = sections[itLetter];
			posToLetter.put(letterToPos.get(letter), itLetter);
		}
		// ooOO00K !

	}

	@Override
	public int getPositionForSection(int section) {
		String letter = sections[section];
		int pos = letterToPos.get(letter);
		//Log.d("getPositionForSection", String.format("%s -> %d", letter, pos));
		return pos;
	}

	@Override
	public int getSectionForPosition(int position) {
		int letter = posToLetter.get(position);
		//Log.d("getSectionForPosition", String.format("%d -> %s", position, sections[letter]));
		return letter;
	}

	@Override
	public Object[] getSections() {

		return sections; // to string will be called each object, to display
		// the letter
	}
}